package com.bawei.lib_base

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.ToastUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import java.io.File

abstract class BaseViewModel<uiIntent:UIIntent>: ViewModel() {
    private val _uiIntent= Channel<UIIntent> {  Channel.UNLIMITED}
    private val _state= MutableStateFlow<UIState>(UIState.OnLoading)
    val state:StateFlow<UIState>
        get() = _state
    init{
        viewModelScope.launch {
            _uiIntent.receiveAsFlow().collect(){
                handeluiIntent(it)
            }

        }
    }
    fun sendUIIntent(intent:UIIntent){
        viewModelScope.launch {
            _uiIntent.send(intent)
        }
    }
    fun httpRequest(request:Flow<Res<Any>>,type: StateType=StateType.DEFAULT){
        viewModelScope.launch {
            request.flowOn(Dispatchers.IO).catch {
                Log.d("TAG", "网络请求失败: ${it.message}")
                ToastUtils.showLong("网络请求失败: ${it.message}")
            }.collect(){
                if (it.code==0){
                    _state.value=UIState.OnSuccess(it.data,type)
                }else{
                    _state.value=UIState.OnError(it.message)
                }
            }
        }
    }
    fun download(url:String,file:File){
        viewModelScope.launch {
            DownLoadUitlis.downLoad(url,file)
                .flowOn(Dispatchers.IO).catch {
                    Log.d("TAG", "下载失败: ${it.message}")
                }.collect(){
                    _state.value=it
                }
        }
    }
    abstract fun handeluiIntent(it: UIIntent)

}